# !/usr/bin/env python
# -*- coding: UTF-8 -*-
# author: xiazhiquan
# date: Jul 24, 2011

import time
import winsound
import urllib2
import logging
import threading

api_url = 'http://iface.qiyi.com/api/iface5?key=ad04b7c798c5ed8a0c0caf79061ae9e5&id=1234567890&include_all=1'
servers = ('202.108.14.201', '220.181.115.202', '220.181.115.201', '202.108.14.202')
format = "%Y-%m-%d %H:%M:%S"
timeout = 15
logfile = time.strftime("%Y-%m-%d") + ".log"
useSound = True

def getLogger():
    logger = logging.getLogger()
    filehandler = logging.FileHandler(logfile)
    streamhandler = logging.StreamHandler()
    fmt = logging.Formatter('[%(asctime)s] %(message)s')
    filehandler.setFormatter(fmt)
    streamhandler.setFormatter(fmt)
    logger.setLevel(logging.DEBUG)
    logger.addHandler(filehandler)
    logger.addHandler(streamhandler)
    return logger


def play_sound():
    count = 1
    while count < 4:
        count += 1
        winsound.Beep(1600, 300)


#def alertPopup(t='Alert Message', msg="Emtpy Msg"):
#    tkMessageBox.showwarning(title=t, message=msg)


def getNow(time_format=format):
    return time.strftime(time_format)


def alert(msg):
    if useSound:
        play_sound()
    else:
    #        alertPopup(msg=msg)
        pass

log = getLogger()

while True:
    try:
        time.sleep(3)
        for server in servers:
            api = api_url.replace('iface.qiyi.com', server)
            url = urllib2.urlopen(api, timeout=timeout)
            # get resp code
            respCode = url.getcode()

            if respCode != 200:
                msg = '%s code is %d' % ( server, respCode)
                alert(msg)
            else:
                msg = '%s is ok' % (server)
            log.info(msg)
    except Exception, e:
        msg = '%s except:[%s]! timeout=%ds' % ( server, e, timeout)
        log.info(msg)
        alert(None)
        continue